package com.whfc.common.util;

import com.whfc.common.enums.FenceType;
import com.whfc.common.geometry.GeometryUtil;
import com.whfc.common.geometry.Point;
import org.apache.commons.lang3.StringUtils;

import java.util.Random;
import java.util.regex.Pattern;

/**
 * @Description: GPS工具
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/8/7 17:43
 */
public class PositionUtil {

    /**
     * 中国的经纬度范围大约为：纬度3.86~53.55，经度73.66~135.05
     */
    private static final double MAX_LNG = 135.05;
    private static final double MIN_LNG = 73.66;
    private static final double MAX_LAT = 53.55;
    private static final double MIN_LAT = 3.86;

    public static final String wgs84 = "wgs84";

    public static final String GCJ02 = "gcj02";

    public static final String bd09ll = "bd09ll";

    public static double pi = 3.1415926535897932384626;

    public static double a = 6378245.0;

    public static double ee = 0.00669342162296594323;

    public static final Pattern POLYGON = Pattern.compile("(\\d+\\.?\\d+)");

    /**
     * 地球半径
     */
    private final static double EARTH_RADIUS = 6378.137;

    /**
     * 84 to 火星坐标系 (GCJ-02) World Geodetic System ==> Mars Geodetic System
     *
     * @param lat
     * @param lng
     * @return
     */
    public static Gps gps84_To_Gcj02(double lat, double lng) {
        if (outOfChina(lat, lng)) {
            return null;
        }
        double dLat = transformLat(lng - 105.0, lat - 35.0);
        double dLng = transformLng(lng - 105.0, lat - 35.0);
        double radLat = lat / 180.0 * pi;
        double magic = Math.sin(radLat);
        magic = 1 - ee * magic * magic;
        double sqrtMagic = Math.sqrt(magic);
        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
        dLng = (dLng * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
        double mgLat = lat + dLat;
        double mgLon = lng + dLng;
        return new Gps(mgLat, mgLon);
    }

    /**
     * * 火星坐标系 (GCJ-02) to 84 * * @param lon * @param lat * @return
     */
    public static Gps gcj_To_Gps84(double lat, double lng) {
        Gps gps = transform(lat, lng);
        double lontitude = lng * 2 - gps.getLng();
        double latitude = lat * 2 - gps.getLat();
        return new Gps(latitude, lontitude);
    }

    /**
     * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换算法 将 GCJ-02 坐标转换成 BD-09 坐标
     *
     * @param gg_lat
     * @param gg_lng
     */
    public static Gps gcj02_To_Bd09(double gg_lat, double gg_lng) {
        double x = gg_lng, y = gg_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * pi);
        double bd_lng = z * Math.cos(theta) + 0.0065;
        double bd_lat = z * Math.sin(theta) + 0.006;
        return new Gps(bd_lat, bd_lng);
    }

    /**
     * * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换算法 * * 将 BD-09 坐标转换成GCJ-02 坐标 *
     *
     * @param bd_lat
     * @param bd_lng
     * @return
     */
    public static Gps bd09_To_Gcj02(double bd_lat, double bd_lng) {
        double x = bd_lng - 0.0065, y = bd_lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * pi);
        double gg_lng = z * Math.cos(theta);
        double gg_lat = z * Math.sin(theta);
        return new Gps(gg_lat, gg_lng);
    }

    /**
     * (BD-09)-->84
     *
     * @param bd_lat
     * @param bd_lng
     * @return
     */
    public static Gps bd09_To_Gps84(double bd_lat, double bd_lng) {

        Gps gcj02 = PositionUtil.bd09_To_Gcj02(bd_lat, bd_lng);
        Gps map84 = PositionUtil.gcj_To_Gps84(gcj02.getLat(), gcj02.getLng());
        return map84;

    }

    /**
     * 判断是否中国范围内的经纬度
     *
     * @param lng
     * @param lat
     * @return
     */
    public static boolean isInChina(Double lng, Double lat) {

        if (lng != null && lng >= MIN_LNG && lng <= MAX_LNG
                && lat != null && lat >= MIN_LAT && lat <= MAX_LAT) {
            return true;
        }
        return false;
    }

    /**
     * 检测坐标点是否在设置范围内
     *
     * @param type
     * @param geomWKT
     * @param lat
     * @param lng
     * @return
     */
    public static boolean contains(Integer type, String geomWKT, Double radius, Double lat, Double lng) {
        if (lat == null || lng == null) {
            return false;
        }

        if (StringUtils.isBlank(geomWKT)) {
            // 检测是否在国内
            return isInChina(lng, lat);
        }
        // 检测是否在设置的电子围栏内
        if (FenceType.POLYGON.value().equals(type)) {
            // 多边形
            return GeometryUtil.isInPolygon(geomWKT, lat, lng);
        } else {
            // 圆形
            return GeometryUtil.isInCircle(geomWKT, radius, lat, lng);
        }
    }


    /**
     * 判断是否中国范围内的经纬度
     *
     * @param lng
     * @param lat
     * @return
     */
    public static boolean outOfChina(Double lng, Double lat) {
        return !isInChina(lng, lat);
    }

    public static Gps transform(double lat, double lng) {
        if (outOfChina(lat, lng)) {
            return new Gps(lat, lng);
        }
        double dLat = transformLat(lng - 105.0, lat - 35.0);
        double dLng = transformLng(lng - 105.0, lat - 35.0);
        double radLat = lat / 180.0 * pi;
        double magic = Math.sin(radLat);
        magic = 1 - ee * magic * magic;
        double sqrtMagic = Math.sqrt(magic);
        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
        dLng = (dLng * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
        double mgLat = lat + dLat;
        double mgLng = lng + dLng;
        return new Gps(mgLat, mgLng);
    }

    public static double transformLat(double x, double y) {
        double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y
                + 0.2 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(y * pi) + 40.0 * Math.sin(y / 3.0 * pi)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(y / 12.0 * pi) + 320 * Math.sin(y * pi / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    public static double transformLng(double x, double y) {
        double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(x * pi) + 40.0 * Math.sin(x / 3.0 * pi)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(x / 12.0 * pi) + 300.0 * Math.sin(x / 30.0 * pi)) * 2.0 / 3.0;
        return ret;
    }


    /**
     * 获取区域内的随机坐标
     *
     * @param point
     * @return
     */
    public static Gps getRandomLatLng(Gps point) {
        Random random = new Random();
        double cirx = point.getLat();
        double ciry = point.getLng();

        double circleR = 0.0005;
        double r2 = Math.pow(circleR, 2);

        double x = (random.nextInt(500) * 0.000001) - circleR;
        double y = (random.nextInt(500) * 0.000001) - circleR;

        if (r2 > Math.pow(x, 2) + Math.pow(y, 2)) {
            return new Gps(cirx + x, ciry + y);
        }
        return getRandomLatLng(point);
    }


    /**
     * 度分秒转经纬度
     *
     * @param dms 116°25'7.85"
     * @return 116.418847
     */
    public static double transformPos(String dms) {
        if (StringUtils.isBlank(dms)) {
            return 0;
        }
        String d = "°";
        String m = "′";
        String s = "″";
        if (!dms.contains(d) || !dms.contains(m) || !dms.contains(s)) {
            return 0;
        }
        dms = dms.trim();
        double dData = Double.parseDouble(dms.split(d)[0]);
        double mData = Double.parseDouble(dms.split(d)[1].split(m)[0]);
        double sData = Double.parseDouble(dms.split(d)[1].split(m)[1].replace(s, ""));
        return dData + mData / 60 + sData / 60 / 60;
    }


    public static void main(String[] args) {

        // 北斗芯片获取的经纬度为WGS84地理坐标 31.426896,119.496145
//        Gps gps = new Gps(30.473787, 114.422017);
//        System.out.println("gps :" + gps);
//        Gps gcj = gps84_To_Gcj02(gps.getLat(), gps.getLng());
//        System.out.println("gcj :" + gcj);
//        Gps star = gcj_To_Gps84(gcj.getLat(), gcj.getLng());
//        System.out.println("star:" + star);
//        Gps bd = gcj02_To_Bd09(gps.getLat(), gps.getLng());
//        System.out.println("bd  :" + bd);
//        Gps gcj2 = bd09_To_Gcj02(bd.getLat(), bd.getLng());
//        System.out.println("gcj :" + gcj2);114.343627,30.507271

//        for (int i = 0; i < 10; i++) {
//            Gps gps = new Gps(30.507271, 114.343627);
//            Gps randomLatLng = getRandomLatLng(gps);
//            System.out.println("randomLatLng :" + randomLatLng);
//        }
//         String wkt = "POLYGON((116.96744 30.850579, 117.19266 30.699551, 116.890536 30.616857, 116.890536 30.616857, 116.96744 30.850579))";
//         System.out.println(contains(wkt, 0d, 0d));
//         System.out.println(POLYGON.matcher(wkt).find());
        String str1 = "(111.440296,35.90028)";
        String str2 = "(111.423218,35.98663)";
        Point startPoint = GeometryUtil.decodePoint(str1);
        Point endPoint = GeometryUtil.decodePoint(str2);

        System.out.println(getDistance(startPoint, endPoint));
    }


    /**
     * 计算两个坐标点之间的距离
     *
     * @param startPoint 开始点坐标
     * @param endPoint   结束点坐标
     * @return 返回两点之间的距离，单位：公里/千米
     */
    public static Double getDistance(Point startPoint, Point endPoint) {
        if (startPoint == null || endPoint == null) {
            return null;
        }
        double startRadLng = rad(startPoint.getLng());
        double startRadLat = rad(startPoint.getLat());
        double endRadLng = rad(endPoint.getLng());
        double endRadLat = rad(endPoint.getLat());

        double a = startRadLat - endRadLat;
        double b = startRadLng - endRadLng;
        double cal = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(startRadLat)
                * Math.cos(endRadLat) * Math.pow(Math.sin(b / 2), 2))) * EARTH_RADIUS;
        return Math.round(cal * 10000D) / 10000D;
    }


    /**
     * 经纬度转化成弧度
     *
     * @param d 经度/纬度
     * @return 弧度
     */
    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }


}
